<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">推广名片</block>
		</cu-custom>
		<view class="margin-top-sm">
			<view v-show="loading" class="promotion-swiper bg-white">
				<view class=" cu-load bg-white loading"></view>
			</view>
			<swiper v-show="!loading" class="card-swiper promotion-swiper square-dot" :indicator-dots="true" :circular="true" @change="cardSwiper" indicator-color="#8799a3"
			 indicator-active-color="#444">
				<swiper-item v-for="(item,index) in swiperList" :key="index" :class="cardCur==index?'cur':''" style="padding-top: 0;padding-bottom: 50rpx;">
					<view class="swiper-item"  style="box-shadow:0px 0px 30px #ebebeb; " @tap="tapShowPoster(item)">
						<image :src="item" mode="scaleToFill" style="z-index: 999;" ></image>
					</view>
				</swiper-item>
			</swiper>
			<view class="padding-tb flex flex-direction padding-lr-xl margin-top">
				<!-- #ifdef H5 -->
				<view class=" text-center">点击图片后长按保存到相册</view>
				<!-- #endif -->
				<!-- #ifndef H5 -->
				<button class="cu-btn lg round" :class="'bg-'+theme.backgroundColor" @click="save">保存到相册</button>
				<!-- #endif -->
			</view>
		</view>
		<poster id="poster" ref='posterRef'  :hide-loading="true" :preload="false"
			@success="onPosterSuccess"
			@fail="onPosterFail">
		</poster>
		<view :class="'cu-modal ' + (posterShow ? 'show ' : '')">
			<view class="cu-dialog ">
				<view class="bg-white" style="height: 1000rpx">
					<image :src="posterUrl" mode="scaleToFill"  class="image-box"></image>
				</view>
				<view class="cu-bar bg-white solid-top show-btn">
					<view class="action margin-0 flex-sub" @tap="posterShow=false">取消</view>
					<!-- #ifdef MP || APP-PLUS -->
					<view class="action margin-0 flex-sub solid-left text-red text-bold" @tap="save">保存到相册</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<view class="action margin-0 flex-sub solid-left  text-bold" >长按图片可保存或分享</view>
					<!-- #endif -->
				</view>
			</view>
		</view>
		<view v-show="showCanvas" style="margin-top: 200px;">
			<canvas canvas-id="qrcode-canvas" />
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const util = require("utils/util.js");
	const { base64src } = require("utils/base64src.js");
	const app = getApp();
	import api from 'utils/api'
	import __config from '@/config/env';

	import poster from "@/components/wxa-plugin-canvas/poster/index";
	import QRCode from "@/components/tki-qrcode/qrcode.js"

	export default {
		components:{
			poster,
		},
		data() {
			return {
				shareCodeUrl: '/pages/home/index',
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				posterUrl: '',  // 当前海报的地址
				cardCur: 0,		// 当前切换的索引
				curIndex: 0,	// 当前生成海报的索引
				posterShow: false,
				isFirst: true,
				showCanvas: true,
				loading: true,
				swiperList: [],
				userInfo: {},
				distributionConfig: {},
				distribution: {},
				posterConfig: {
					width: 900,
					height: 1550,
					backgroundColor: '#ffffff',
					debug: false,
				},
				qrCodeImgRes: '',//二维码或者小程序码图片
				imgUrl: ''
			}
		},
		onLoad(){
			this.userInfo = uni.getStorageSync('user_info');
			this.initData()
		},
		onShow(){
		},
		onHide(){
			uni.hideLoading();
		},
		methods: {
			tapShowPoster(url){

				this.posterUrl = url
				this.posterShow = true
			},
			renderSuccess(res){
				this.swiperList.push(res)
			},
			save(){
				var that = this;
				this.posterUrl = this.swiperList[this.cardCur]
				uni.saveImageToPhotosAlbum({
					filePath: that.posterUrl,
					success(res) {
						uni.showToast({
							title: '保存到相册成功~',
							icon: 'none',
							duration: 3000
						});
					}
				});
			},
			// cardSwiper
			cardSwiper(e) {
				this.cardCur = e.detail.current
			},
			qrCodeResult(res){
				this.imgUrl = res;
			},
			initData(){
				//分销设置
				api.distributionConfig().then(res => {
					if(res.data) {
						this.distributionConfig = res.data
						// 根据图片生成海报
						this.onCreatePoster();
					}
				});
				api.distributionuser(this.userInfo.id).then(res => {
					if(res.data) {//是分销员
						this.distribution = res.data
					}
				});
			},
			/**
			 * 异步生成海报
			 */
			onCreatePoster() {
				// #ifdef MP
					api.qrCodeUnlimited({
						theme: app.globalData.theme,  // 全局颜色变量
						page: 'pages/home/index', // 当前页面路径
						scene: '0&' + this.userInfo.userCode // 约定：由于微信小程序参数长度限制，固第二个参数固定为sharer_code，首页接收分享人UserCode值的时候,默认取第二个参数的值，所以就默认设置第一个值为0
					}).then(res => {
						uni.showToast({
							title: '正在加载海报...',
							icon: 'loading',
							duration: 6000
						});
						base64src(res.data, res => {
							this.qrCodeImgRes = res;
							this.loading = false;
							if(this.distributionConfig.picUrls&&this.distributionConfig.picUrls.length>0){
								this.startCreatePoster(this.distributionConfig.picUrls[0]);
							}
						});
					});
				// #endif
				// #ifdef H5
					this.$nextTick(()=>{
						let shareUrl =  util.setH5HomeShareUrl();;
						this.qrCodeSave(shareUrl)
					})
				// #endif
				// #ifdef APP-PLUS
				api.wxAppConfig(__config.wxAppId).then(res => {
					if(res.data.data&&res.data.data.isComponent=='1') {
						let shareUrl = util.setAppPlusHomeShareUrl(res.data.data);
						this.qrCodeSave(shareUrl)
					}else{
						let shareUrl = util.setAppPlusHomeShareUrl();
						this.qrCodeSave(shareUrl)
					}

				});
				// #endif
			},
			qrCodeSave(shareUrl){
				let that = this
				new QRCode({
					context: that, // 上下文环境
					canvasId: 'qrcode-canvas', // canvas-id
					usingComponents: false, // 是否是自定义组件
					showLoading: false, // 是否显示loading
					loadingText: false, // loading文字
					text: shareUrl, // 生成内容
					size: uni.upx2px(170), // 二维码大小
					background: '#ffffff', // 背景色
					foreground: '#000000', // 前景色
					pdground: '#000000', // 定位角点颜色
					correctLevel: 2, // 容错级别
					image: '/static/public/logo.png', // 二维码图标
					imageSize: 7,// 二维码图标大小
					cbResult: function (res) { // H5需要先生成二维码后 才能生成海报
						that.qrCodeImgRes = res;
						that.showCanvas = false
						that.loading = false;
						if(that.distributionConfig.picUrls && that.distributionConfig.picUrls.length>0){
							that.startCreatePoster(that.distributionConfig.picUrls[0]);
						}
					},
				});
			},

			startCreatePoster(itemImg){ // 开始 生成海报
				uni.showLoading();
				// 需要注意：分享海报的图片方法会传入res对象,用 qrCodeName: 'qrCodeName'属性进行唯一标识
				//海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
				var width = 900
				var posterConfig = {
					width: width,
					height: 1570,
					backgroundColor: '#ffffff',
					debug: false,
					texts: [
						{
							x: 372,
							y: 1340,
							fontSize: 28,
							baseLine: 'middle',
							text: this.userInfo.nickName+ "邀请您加入",
							width: 570,
							lineNum: 1,
							color: '#02071d',
							zIndex: 200
						},
						{
							x: 372,
							y: 1400,
							fontSize: 28,
							baseLine: 'middle',
							text:  "邀请您加入JooLun商城",
							width: 570,
							lineNum: 1,
							color: '#02071d',
							zIndex: 200
						},
						{
							x: 270,
							y: 1590,
							fontSize: 20,
							baseLine: 'middle',
							text: "—— 长按识别或扫描二维码进入 ——",
							width: 570,
							lineNum: 1,
							color: '#acacac',
							zIndex: 200
						},
					],
					images: [
						{
							width: width,
							height: 1200,
							x: 0,
							y: 0,
							url: itemImg,
							zIndex: 999
						},
					]
				};
				// #ifdef MP
				posterConfig.images.push({
							width: 220,
							height: 220,
							x: 92,
							y: 1260,
							url: this.qrCodeImgRes,
						})
				// #endif
				// #ifdef H5 || APP-PLUS
				posterConfig.images.push({
							width: 800,
							height: 400,
							x: 80,
							y: 1280,
							url: this.qrCodeImgRes,
						})
				// #endif
				this.$refs.posterRef.onCreate2(true, posterConfig) // 入参：true为抹掉重新生成
			},
			onPosterSuccess(e) {
				uni.hideLoading();
				// #ifdef H5
					//H5兼容问题，第一张图片生成的有问题，所以重新生成一下
					if(this.curIndex==0 && this.isFirst){
						this.isFirst = false;
						this.startCreatePoster(this.distributionConfig.picUrls[0]);
					}else{
						this.swiperList.push(e)
						this.curIndex = this.curIndex+1
						if(this.distributionConfig.picUrls&&this.distributionConfig.picUrls.length>this.curIndex){
							this.startCreatePoster(this.distributionConfig.picUrls[this.curIndex]);
						}
					}
				// #endif
				// #ifndef H5
					this.swiperList.push(e)
					this.curIndex = this.curIndex+1
					if(this.distributionConfig.picUrls&&this.distributionConfig.picUrls.length>this.curIndex){
						this.startCreatePoster(this.distributionConfig.picUrls[this.curIndex]);
					}
				// #endif
			},
			onPosterFail(err) {
				console.error(err);
			},
		}
	}
</script>

<style>
	page{
		background-color: #FFFFFF;
	}

	.promotion-swiper {
		height: 1000rpx !important;
	}

	.image-box{
		height: 100%;
		width: 100%;
	}

</style>
